import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
from keras.optimizer_v1 import RMSprop
from sklearn import datasets
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

import tensorflow as tf
from keras import models
from keras import layers
from keras.models import load_model
from keras.layers import Dense
from keras.layers import Dropout
from sklearn import preprocessing

np.random.seed(1234)

data = pd.read_csv("cs.csv")
data = data.dropna(axis=0, how='any')

data = np.array(data)

# 加载数据
x_train = data[0:400, :-1]
y_train = data[0:400, -1:]
x_test = data[400:, :-1]
y_test = data[400:, -1:]


x_train = preprocessing.scale(x_train)
scaler = preprocessing.StandardScaler().fit(x_train)
x_test = scaler.transform(x_test)

print(x_train.shape)
print(x_test.shape)

# kernel_initializer = tf.initializers.TruncatedNormal(mean=0.0, stddev=0.05),

model = models.Sequential()
model.add(Dense(128, activation="relu",
                input_shape=(x_train.shape[1],)))
model.add(Dense(512, activation="relu"))
model.add(Dense(512, activation="relu"))
model.add(Dense(512, activation="relu"))
model.add(Dense(512, activation="relu"))
model.add(Dense(512, activation="relu"))
model.add(Dense(256, activation="relu"))
model.add(Dense(1))  # 最后的密集连接层，不用激活函数

model.compile(optimizer="rmsprop",  # 优化器
              loss="mse",  # 损失函数
              metrics=["mae"]  # 评估指标：平均绝对误差
              )
model.summary()

epoch = 1000
split1 = 0.001
batch = 2
history = model.fit(x_train,  # 特征
                    y_train,  # 输出
                    epochs=epoch,  # 模型训练100轮
                    validation_split=split1,
                    batch_size=batch,
                    verbose=1  # 静默模式；如果=1表示日志模式，输出每轮训练的结果
                    )
score = model.evaluate(x_test, y_test)
model.save("model.h5")
print(score[1])
pre = model.predict(x_test)
plt.plot(pre, color="red", linewidth=2)
plt.plot(y_test, color="green", linewidth=2)
plt.show()

# plt.plot(range(800,1000), history.history['loss'][800:])
# plt.plot(range(800,1000), history.history['mse'][800:])
# plt.plot(range(800,1000), history.history['val_loss'][800:])
# plt.plot(range(800,1000), history.history['val_mse'][800:])
# plt.legend(['loss', 'mse', 'val_loss', 'val_mse'], loc='upper left')
# plt.show()

# print(history.history.keys())
#
# pre = model.predict(x_test)
# print(pre)
#
# plt.plot(range(x_test.shape[0]), pre)
# plt.plot(range(x_test.shape[0]), y_test)
#
# plt.legend(['pre', 'test'], loc='upper left')
# pre = pd.DataFrame(np.array(pre))
# pre.to_csv("result.csv", index=False, header=False)
#
# plt.show()
